package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        List<String> input = new ArrayList<>(List.of(username, password));

        // 创建 ABT_System 实例
        ABT_System abtSystem = new ABT_System();

        // 调用 login 函数进行登录验证
        boolean isLoggedIn = false;
        try {
            isLoggedIn = abtSystem.Login(input);
        } catch (ABT_SystemException e) {
            System.err.println("出现异常：" + e.getMessage());
        }

        if (isLoggedIn) {
            // 登录成功，将用户信息保存到会话中
            HttpSession session = request.getSession();

            // 重定向到登录成功页面
            if (abtSystem.getLogFlag() == 1) {
                Admin admin = new Admin();
                admin.setUid(abtSystem.getUid());
                // 存储 Admin 对象到 session
                session.setAttribute("admin", admin);
                response.sendRedirect("adminMain.jsp");
            } else {
                User user = new User();
                user.setUid(abtSystem.getUid());
                // 存储 User 对象到 session
                session.setAttribute("user", user);
                response.sendRedirect("userMain.jsp");
            }
        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("errorMessage", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通常将 GET 请求转发到 POST 处理方法
        doPost(request, response);
    }
}